package com.yin.jia.liang.controller;

import com.yin.jia.liang.entity.*;
import com.yin.jia.liang.service.GongGaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("gonggao")
public class GongGaoController {

    @Autowired
    GongGaoService gongGaoService;

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String index(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            return "gonggao/add";
        } else {
            return "redirect:/own";
        }
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String update(HttpSession session, Model model, @PathVariable Integer id) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            GongGao gongGao = gongGaoService.findById(id);
            model.addAttribute("gonggao", gongGao);
            return "gonggao/add";
        } else {
            return "redirect:/own";
        }
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String index(@ModelAttribute GongGao gongGao, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            if (gongGao.getId() == null) {
                gongGaoService.save(gongGao);
                return "redirect:/own";
            }

            gongGaoService.update(gongGao);
        }
        return "redirect:/";
    }

    @RequestMapping(value = "del/{id}", method = RequestMethod.GET)
    public String del(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            gongGaoService.delete(id);
        }
        return "redirect:/";
    }
}
